﻿using System.Collections.Generic;
using System.Linq;
using Android.Content.Res;
using Android.Views;

namespace Moven.Droid
{
	public static class ViewUtils
	{
		public static List<T> FindViews<T>(this ViewGroup viewGroup) where T : View
		{
			var result = new List<T>();

			var count = viewGroup.ChildCount;
			for (int i = 0; i < count; i++)
			{
				var child = viewGroup.GetChildAt(i);
			    var item = child as T;
			    if (item != null)
				{
					result.Add(item);
				}
				else if (child is ViewGroup)
				{
					var innerResult = FindViews<T>(child as ViewGroup);
					if (innerResult != null)
					{
						result.AddRange(innerResult);
					}
				}
			}
			return result;
		}

		public static T FindView<T>(this ViewGroup viewGroup) where T : View => FindViews<T>(viewGroup).FirstOrDefault();

		public static int DpToPx(this double dp)
		{
			return (int)(dp * Resources.System.DisplayMetrics.Density);
		}

		public static int DpToPx(this int dp)
		{
			return (int)(dp * Resources.System.DisplayMetrics.Density);
		}
	}
}
